﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Resources;
using System.Windows.Threading;

namespace KnowledgeKiosk
{
    /// <summary>
    /// Retro digital clock that displays date and time
    /// </summary>
    public partial class DigitalClockControl : UserControl
    {
        public static readonly DependencyProperty DateAndTimeProperty =
            DependencyProperty.Register("DateAndTime", typeof (DateTime), typeof (DigitalClockControl),
                                        new PropertyMetadata(DateTime.Now));

        public DigitalClockControl()
        {
            InitializeComponent();
            FixFontReferences();
            InitializeClock();
        }

        /// <summary>
        /// Gets or sets the date and time of the clock
        /// </summary>
        public DateTime DateAndTime
        {
            get { return (DateTime) GetValue(DateAndTimeProperty); }
            set { SetValue(DateAndTimeProperty, value); }
        }

        /// <summary>
        /// Fixes references to the embedded font used by the digital clock.
        /// </summary>
        public void FixFontReferences()
        {
            var fontUri = new Uri(@"/KnowledgeKiosk;component/Fonts/Fonts.zip", UriKind.Relative);
            StreamResourceInfo fontsArchive = Application.GetResourceStream(fontUri);
            StreamResourceInfo fontResource = Application.GetResourceStream(fontsArchive,
                                                                            new Uri(@"DS-Digital1.subset.ttf",
                                                                                    UriKind.Relative));
            var fs = new FontSource(fontResource.Stream);
            glyphsBack.FontSource = fs;
            glyphsFront.FontSource = fs;
        }

        /// <summary>
        /// Initializes the clock by creating a DispatcherTimer that updates the date and time of the clock
        /// with the current date and time every second. 
        /// </summary>
        public void InitializeClock()
        {
            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += delegate { DateAndTime = DateTime.Now; };
            timer.Start();
        }
    }
}